using System;
using System.IO;
using System.IO.Compression;
using System.Web;

namespace Wild2.Models
{
    public class HttpCompressionModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }
        private void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            if (app.Request.Url.ToString().ToLower().IndexOf("aspx", StringComparison.Ordinal) == -1) return;
            string encodings = app.Request.Headers.Get("Accept-Encoding");
            if (encodings == null) return;
            Stream basestream = app.Response.Filter;
            encodings = encodings.ToLower();
            if (encodings.Contains("gzip"))
            {
                app.Response.Filter = new GZipStream(basestream, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "gzip");
            }
            else if (encodings.Contains("deflate"))
            {
                app.Response.Filter = new GZipStream(basestream, CompressionMode.Compress);
                app.Response.AppendHeader("Content-Encoding", "deflate");
            }
        }
        public void Dispose()
        {

        }
    }
}
